package com.knight.controller;

import com.knight.dto.FileInfo;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping(value = "/file")
public class FileController {

    private static final String FOLDER = "D:\\gitProject\\imooc-security\\imooc-security-demo\\src\\main\\java\\com" +
            "\\knight" +
            "\\controller\\";

    /**
     * 文件上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping
    public FileInfo uploadeFile(MultipartFile file) throws IOException {

        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getSize());

        File localFile = new File(FOLDER + System.currentTimeMillis() + ".txt");
        file.transferTo(localFile);

        return new FileInfo(localFile.getName(), localFile.getAbsolutePath());
    }

    @GetMapping("/{id}")
    public void download(@PathVariable(value = "id") String id, HttpServletRequest request,
                         HttpServletResponse response) {
        try (InputStream inputStream = new FileInputStream(new File(FOLDER, id + ".txt"));
             OutputStream outputStream = response.getOutputStream()) {
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=test.txt");
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
